<?php

class DataDir {

    private $path;
    private $arrFilenames;

    public function __construct($path) {
        Dir::checkExistsAndReadable($path);
        $this->path = Dir::addEndslash($path);
    }

    private function readFilelist() {

        $this->arrFilenames = array_filter(
            Dir::getFilenames($this->getPath()),
            array($this, 'isDataFile')
        );

        natsort($this->arrFilenames);
    }

    private function isDataFile($filename) { return preg_match('~^\d+\.?~', $filename); }

    public function getPath()  { return $this->path; }
    public function hasFiles() { return count($this->arrFilenames) > 0; }

    public function getLastFiles($nFiles) {

        if (!$this->hasFiles())
            throw new Exception('no files in ' . get_class() . ' "' . $this->getPath() .'"');

        $arrFiles = array();
        foreach (array_slice($this->arrFilenames, $nFiles) as $filename) {
            $arrFiles[] = $this->getPath() . $filename;
        }

        return $arrFiles;
    }

    public function getLastFilename() {
        return reset($this->getLastFiles(1));
    }

    public function getLastFreeFilename($defaultPostfix = '') {

        if (!$this->hasFiles()) {
            return $this->getPath() . '0' . $defaultPostfix;
        }

        $lastFilename = $this->getLastFilename();

        if (!preg_match('~^(\d)(.*)$~', $lastFilename, $m))
            throw new Exception("Incorrect last filename: '$lastFilename'");

        list($null, $filenameHead, $filenameTail) = $m;
        $lastFreeFilename = ($filenameHead + 1) . $filenameTail;

        if (file_exists($this->getPath() . $lastFreeFilename))
            throw new Exception("'$lastFreeFilename' already exists");

        return $lastFreeFilename;
    }

}

?>